package com.atguigu.datastream.day05;

import com.atguigu.datastream.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * ClassName: Flink03_ProcessTimeWindow_ReduceFunction
 * Package: com.atguigu.day05
 * Description:
 *            规约函数reduce
 * @Author ChenJun
 * @Create 2023/4/11 16:32
 * @Version 1.0
 */
public class Flink03_ProcessTimeWindow_ReduceFunction {
    public static void main(String[] args) throws Exception {

        //1. 创建流的运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2. 从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        // TODO 将读取的数据转为javaBean
        SingleOutputStreamOperator<WaterSensor> streamOperator = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String s) throws Exception {
                String[] split = s.split(",");

                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });

        //3.将相同的key聚合到一起
        KeyedStream<WaterSensor, Tuple> keyedStream = streamOperator.keyBy("id");

        //4 开启一个基于处理时间的滚动窗口，窗口大小为5S
        WindowedStream<WaterSensor, Tuple, TimeWindow> window = keyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(5)));

        //5. TODO 调用增量聚合函数Reduce对vc做累加
        SingleOutputStreamOperator<WaterSensor> reduce = window.reduce(new ReduceFunction<WaterSensor>() {
            @Override
            public WaterSensor reduce(WaterSensor w1, WaterSensor w2) throws Exception {
                System.out.println("reduce..........");
                return new WaterSensor(w1.getId(), w1.getTs(), w1.getVc() + w2.getVc());
            }
        });


        reduce.print();

        env.execute();


    }
}
